let markupBasePath = "_www/static/draws/";
let markupBaseDir = "avred";

export const getMarkupFilePathEntry = (inPlantDir, inFileName, inDate) => {
	return new Promise((resolve, reject) => {
		let readEntriesOk = (e) => {
			for (let i = 0; i < e.length; i++) {
				console.log(e[i].name);
				if (e[i].name.indexOf(inFileName) != -1 && e[i].name.indexOf(inDate) != -1) {
					console.log(" find  it  !")
					return e[i];
				}
			}
			return null;
		};

		console.log("getMarkupFilePathEntry   --- 0  " + inPlantDir);
		// let inPath = markupBasePath + inPlantDir + '/' + markupBaseDir;
		let inPath = '_doc/';

		console.log("getMarkupFilePathEntry   --- 1  " + inPath);
		console.log("getMarkupFilePathEntry   --- 2  " + inFileName);
		console.log("getMarkupFilePathEntry   --- 3  " + inDate);

		plus.io.resolveLocalFileSystemURL(inPath,
			function(entry) {
				// 可通过entry对象操作test.html文件 
				if (!entry.isDirectory) {
					console.log("getMarkupFilePathEntry   --- re --- !entry.isDirectory")
					return;
				}

				var directoryReader = entry.createReader();
				directoryReader.readEntries(function(e) {
						let re = readEntriesOk(e);
						let reUrl = re.toRemoteURL();
						console.log("reurl = " + reUrl);
						resolve(reUrl);
					},
					function(e) {
						console.log("getMarkupFilePathEntry   --- directoryReader --- fail --- 0")
						console.log(e)
						reject(e);
					}
				);

			},
			function(e) {
				console.log("getMarkupFilePathEntry   --- error")
				console.log(e);
				reject(e);
			});
	})
}

/**
 * 新建、保存markup内容
 * plantDir plt对应的路径
 * 文件名
 * 日期？
 * 写入内容
 */
export const saveMarkupFile = (inPlantDir, inFileName, inDate, inData) => {
	return new Promise((resolve, reject) => {
		// let inPath = markupBasePath + inPlantDir + '/' + markupBaseDir;
		let inPath = '_doc/';

		console.log("saveMarkupFile   --- 1  " + inPath);
		console.log("saveMarkupFile   --- 2  " + inFileName);
		console.log("saveMarkupFile   --- 3  " + inDate);


		plus.io.resolveLocalFileSystemURL(inPath,
			function(entry) {
				// 可通过entry对象操作test.html文件 
				if (!entry.isDirectory) {
					console.log("saveMarkupFile   --- re --- !entry.isDirectory")
					return;
				}

				// 136-E001.dtl-20210425.xml
				let tempFile = inFileName + '.dtl-' + inDate + '.xml';
				entry.getFile(tempFile, {
					create: true,
					// exclusive: true
				}, function(fileEntry) {					
					fileEntry.createWriter( function ( writer ) {
						writer.onwrite = function ( e ) {
							console.log( "saveMarkupFile ---- Write data success!" );
						};
						// Write data to the end of file.
						// writer.seek( writer.length );
						writer.seek( 0 );
						writer.write( inData );
						
						resolve("0");
					}, function ( e ) {
						reject(e);
					} );
				});

			},
			function(e) {
				console.log("saveMarkupFile   --- error")
				console.log(e);
				reject(e);
			});



	})
}
